import React from "react";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import { ComponentInfoType } from "../../../store/componentsReducer";
import { getComponentConfByType } from "../../components/QuestionComponents";
import styles from "./ComponentList.module.scss";
import classNames from "classnames";

type PropsType = {
  config: {
    selectedComponentId: string;
    setSelectedComponentId: (id: string) => void;
    setSelectedComponentType: (type: string) => void;
  };
};

function genComponent(componentInfo: ComponentInfoType) {
  const { type, props } = componentInfo;
  const componentConf = getComponentConfByType(type);

  if (componentConf === null) return null;
  const { Component } = componentConf;

  return <Component {...props} />;
}

const EditCanvas: React.FC<PropsType> = (props: PropsType) => {
  const {
    config: {
      selectedComponentId,
      setSelectedComponentId,
      setSelectedComponentType,
    },
  } = props;
  const { componentList } = useGetComponentInfo();

  return (
    <div className={styles.canvas}>
      {componentList
        .filter((c) => !c.isHidden)
        .map((c) => {
          const { id, type } = c;
          const wrapperDefaultClassName = styles["component-wrapper"];
          const selectedClassName = styles.selected;
          const hoverClassName = styles.hover;
          const wrapperClassName = classNames({
            [wrapperDefaultClassName]: true,
            [selectedClassName]: selectedComponentId === id,
            [hoverClassName]: true,
          });

          return (
            <div
              key={id}
              className={wrapperClassName}
              onClick={() => {
                if (selectedComponentId === id) {
                  setSelectedComponentId("");
                  setSelectedComponentType("");
                } else {
                  setSelectedComponentId(id);
                  setSelectedComponentType(type);
                }
              }}
            >
              <div className={styles.component}>{genComponent(c)}</div>
            </div>
          );
        })}
    </div>
  );
};

export default EditCanvas;
